package org.example.postgraduateproject.Utils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class jdbcUtils {
    // 执行查询操作
    public static ResultSet executeQuery(Connection conn, StringBuilder sql, Object... params) {
        PreparedStatement pst = null;
        ResultSet rst = null;
        try {
            pst = conn.prepareStatement(sql.toString());
            for (int i = 0; i < params.length; i++) {
                pst.setObject(i + 1, params[i]);
            }
            rst = pst.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rst;
    }

    // 执行更新操作（INSERT、UPDATE、DELETE）
    public static int executeUpdate(Connection conn, StringBuilder sql, Object... params) {
        PreparedStatement pst = null;
        int n = 0;
        try {
            pst = conn.prepareStatement(sql.toString());
            for (int i = 0; i < params.length; i++) {
                pst.setObject(i + 1, params[i]);
            }
            n = pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return n;
    }
}